package com.apes.enquiry.supplier.baturu.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.enquiry.supplier.baturu.model.BaturuAccountInfo;
import com.apes.enquiry.supplier.baturu.repository.BaturuAccountInfoRepository;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.jpa.spec.PredicateBuilder;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("baturuAccountInfoService")
public class BaturuAccountInfoService {
    @Autowired
    private BaturuAccountInfoRepository baturuAccountInfoRepository;
    @Autowired
    private EnumerationRepository enumerationRepository;

    public BaturuAccountInfo create(SimpleRequest request) {
        BaturuAccountInfo baturuAccountInfo = request.getO(BaturuAccountInfo.class);
        List<BaturuAccountInfo> baturuAccounts = baturuAccountInfoRepository.findAll(JpaDsl.toCriteriaByEq("storeNumber", baturuAccountInfo.getStoreNumber()));
        if (baturuAccounts.size() > 0) throw new RuntimeException("门店已存在对照信息！");

        List<BaturuAccountInfo> baturuUniqueSigns = baturuAccountInfoRepository.findAll(JpaDsl.toCriteriaByEq("baturuUniqueSign", baturuAccountInfo.getBaturuUniqueSign()));
        if (baturuUniqueSigns.size() > 0) {
            baturuUniqueSigns.stream().map(baturuAccountInfo1 -> {return baturuAccountInfo1.getStoreNumber();}).collect(Collectors.toList());
            throw new RuntimeException("唯一标识符已存在！门店编码：" + baturuUniqueSigns.stream().map(baturuAccountInfo1 -> {return baturuAccountInfo1.getStoreNumber();}).collect(Collectors.toList()).toString());
        }

        baturuAccountInfo.setId(SpringManager.getBean(SequenceService.class).getId("mas_baturu_account_info"));
        baturuAccountInfo.setAccountStatus(enumerationRepository.findByTypeAndCode("accountStatus", baturuAccountInfo.getAccountStatus().getCode()));
        return baturuAccountInfoRepository.saveAndFlush(baturuAccountInfo);
    }

    public BaturuAccountInfo update(SimpleRequest request) {
        BaturuAccountInfo baturuAccountInfo = request.getO(BaturuAccountInfo.class);
        baturuAccountInfo.setAccountStatus(SpringManager.getBean(EnumerationRepository.class).findByTypeAndCode("accountStatus", baturuAccountInfo.getAccountStatus().getCode()));
        return baturuAccountInfoRepository.saveAndFlush(baturuAccountInfo);
    }


    public Map accordStoreFind(SimpleRequest request) {
        JSONObject geJo = request.getJO();
        return baturuAccountInfoRepository.accordStoreFind(geJo.getString("storeId"));
    }
    public String queryUserKey(String storeId) {
        Map findUserKey = baturuAccountInfoRepository.accordStoreFind(storeId);
        if (findUserKey.isEmpty()) return "";
        return findUserKey.get("BATURU_UNIQUE_SIGN").toString();
    }

    // 根据条件查找
    public Map accordConditionFindAll(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        JSONArray conditions = request.getJO().getJSONArray("condition");
        for (int i = 0; i < conditions.size(); i++) {
            String field = conditions.getJSONObject(i).getString("field");
            if (field.equals("accountStatus.id")) {
                Enumeration enumeration = enumerationRepository.findByTypeAndCode("accountStatus", conditions.getJSONObject(i).getString("value"));
                conditions.getJSONObject(i).put("value", enumeration.getId());
                break;
            }
        }

        Pageable pageable = new PageRequest(getJO.getIntValue("page"), getJO.getIntValue("size"));
        Page<BaturuAccountInfo> baturuAccountInfoPage = baturuAccountInfoRepository.findAll(this.appendCondi(conditions), pageable);

        return MapUtil.mapper("content", baturuAccountInfoPage.getContent(), "total", ((PageImpl) baturuAccountInfoPage).getTotalElements());
    }

    public Map findAll(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        Pageable pageable = new PageRequest(getJO.getIntValue("page"), getJO.getIntValue("size"));
        Page<BaturuAccountInfo> baturuAccountInfoPage = baturuAccountInfoRepository.findAll(pageable);
        return MapUtil.mapper("content", baturuAccountInfoPage.getContent(), "total", ((PageImpl) baturuAccountInfoPage).getTotalElements());
    }


    // 拼接查询条件
    public Specification appendCondi(JSONArray condition) {
        PredicateBuilder predicateBuilder = new PredicateBuilder(Predicate.BooleanOperator.AND);
        condition.forEach(singleCondi -> {
            JSONObject condiObj = (JSONObject) singleCondi;
            predicateBuilder.eq(condiObj.getString("field"), condiObj.get("value"));
        });
        Specification specification = predicateBuilder.build(false);
        return specification;
    }


}
